package com.demo.xj_plane.controller;

import com.demo.xj_plane.common.utils.GlobalConstant;
import com.demo.xj_plane.common.utils.ResponseJson;
import com.demo.xj_plane.entity.XjSelfObsEntity;
import com.demo.xj_plane.service.XjLiveSaService;
import com.demo.xj_plane.service.XjMesFcService;
import com.demo.xj_plane.service.XjSelfObsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/xjContent")
@Api(value = "获取自观和报文相关数据", tags = {"获取自观和报文相关接口"})
@Slf4j
public class XjContentController {

    @Autowired
    private XjSelfObsService xjSelfObsService;

    @Autowired
    private XjMesFcService xjMesFcService;

    @Autowired
    private XjLiveSaService xjLiveSaService;

    /**
     * 获取最新报文
     *
     * @param cccc
     * @return
     */
    @GetMapping(value = "/getLatestData")
    @ApiOperation(value = "1、获取最新报文", notes = "务必提交json格式")
    public ResponseJson getLatestContent(@RequestParam("cccc") String cccc) {
        if (cccc == null || cccc == "") {
            ResponseJson.fail("请传入正确的机场四字码");
        }
        // 获取最新报文，FCFT为一组，SA为一组，SP为一组
        Map<String, String> contentMap = new HashMap<>();
        // fc/ft
        String fcContent = xjMesFcService.selectLatestData(cccc);
        contentMap.put("FC", fcContent);
        // sa
        String saContent = xjLiveSaService.selectLatestData(cccc, "SA");
        contentMap.put("SA", saContent);
        // sp
        String spContent = xjLiveSaService.selectLatestData(cccc, "SP");
        contentMap.put("SP", spContent);

        // 返回响应
        return ResponseJson.success(contentMap);
    }

    /**
     * 获取过去24小时的所有报文
     *
     * @return
     */
    @GetMapping(value = "/getLast24HoursData")
    @ApiOperation(value = "2、获取过去24小时的所有报文", notes = "务必提交json格式")
    public ResponseJson getLast24HoursContents() {
        // 获取当前时间，世界时
        LocalDateTime currentTime = LocalDateTime.now(ZoneOffset.UTC);
        // 减去 24 小时
        LocalDateTime timeMinus24Hours = currentTime.minusHours(24);
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        // 格式化日期
        String curDate = timeMinus24Hours.format(formatter);
        // 获取过去24小时报文，FCFT为一组，SA为一组，SP为一组
        Map<String, List<String>> contentMap = new HashMap<>();
        // fc/ft
        List<String> fcContent = xjMesFcService.selectContentLast24Hours(curDate);
        contentMap.put("FC", fcContent);
        // sa
        List<String> saContent = xjLiveSaService.selectContentLast24Hours("SA", curDate);
        contentMap.put("SA", saContent);
        // sp
        List<String> spContent = xjLiveSaService.selectContentLast24Hours("SP", curDate);
        contentMap.put("SP", spContent);

        // 返回响应
        return ResponseJson.success(contentMap);
    }

    /**
     * 获取机场最新自观数据
     *
     * @param cccc
     * @return
     */
    @GetMapping(value = "/getAwos")
    @ApiOperation(value = "3、获取最新自观数据", notes = "务必提交json格式")
    public ResponseJson getAwos(@RequestParam("cccc") String cccc) {
        if (cccc == null || cccc == "") {
            ResponseJson.fail("请传入正确的机场四字码");
        }
        // 获取最新自观数据
        Map<String, Object> dataMap = new HashMap<>();
        List<XjSelfObsEntity> obsLst = xjSelfObsService.selectLatestData(cccc);
        dataMap.put("data", obsLst);
        // 封装机场跑道
        if (obsLst != null && obsLst.size() > 0) {
            dataMap.put("RNO", obsLst.get(0).getRno());
        }

        // 返回响应
        return ResponseJson.success(dataMap);
    }

    @GetMapping(value = "/getAwosLine")
    @ApiOperation(value = "4、获取自观数据折线图", notes = "默认一个小时")
    public ResponseJson getAwosLine(@RequestParam("cccc") String cccc) {
        if (cccc == null || cccc == "") {
            ResponseJson.fail("请传入正确的机场四字码");
        }
        // 默认折线图时间
        LocalDateTime currentTime = LocalDateTime.now(ZoneOffset.UTC);
        // 减去 1 小时
        LocalDateTime timeMinus24Hours = currentTime.minusHours(1);
        // 20分钟前（如需）
        // LocalDateTime timeMinus20Minutes = currentTime.minusMinutes(20);
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化日期
        String curDate = timeMinus24Hours.format(formatter);
        // 获取最新自观数据
        Map<String, Object> dataMap = new HashMap<>();
        List<XjSelfObsEntity> obsLineLst = xjSelfObsService.selectLineData(cccc, curDate);
        dataMap.put("data", obsLineLst);

        // 返回响应
        return ResponseJson.success(dataMap);
    }

    @GetMapping(value = "/getAllPlaneLatestData")
    @ApiOperation(value = "5、获取所有机场的所有最新报文", notes = "务必提交json格式")
    public ResponseJson getAllPlaneLatestData() {
        // 查询所有机场的最新数据
        List<String> aaLst = GlobalConstant.allXjPlaneList;
        List<XjSelfObsEntity> latestDataList = xjSelfObsService.selectAllPlane(aaLst);
        // 返回结果
        List<Map<String, Object>> result = new ArrayList<>();
        // 循环处理每个机场的最新数据
        /*for (XjSelfObsEntity entity : latestDataList) {
            String cccc = entity.getCccc();
            String pointCode = entity.getPointCode();
            String dateTime = entity.getODateTime();

            // 查询上一条记录
            XjSelfObsEntity previousData = xjSelfObsService.findPreviousData(cccc, pointCode, dateTime);
            // 封装剪头 arrow
            String arrow = "UNKNOWN";
            if(previousData != null){
                if(entity.getWindF10() > previousData.getWindF10()){
                    arrow = "UP";
                }
                if(entity.getWindF10() < previousData.getWindF10()){
                    arrow = "LOW";
                }
                if(entity.getWindF10() == previousData.getWindF10()){
                    arrow = "EQUAL";
                }

            }
            entity.setArrow(arrow);

            // 添加到结果中
            Map<String, Object> record = new HashMap<>();
            record.put("CCCC", entity.getCccc());
            record.put("data", entity);
            result.add(record);

        }*/
        // 创建一个用于存储相同CCCC的映射
        Map<String, List<XjSelfObsEntity>> ccccMap = new HashMap<>();
        for (XjSelfObsEntity entity : latestDataList) {
            String cccc = entity.getCccc();
            String pointCode = entity.getPointCode();
            String dateTime = entity.getODateTime();

            // 查询上一条记录
            XjSelfObsEntity previousData = xjSelfObsService.findPreviousData(cccc, pointCode, dateTime);

            // 封装箭头 arrow
            String arrow = "UNKNOWN";
            if (previousData != null) {
                if (entity.getWindF10() > previousData.getWindF10()) {
                    arrow = "UP";// 大于
                } else if (entity.getWindF10() < previousData.getWindF10()) {
                    arrow = "LOW";// 小于
                } else {
                    arrow = "EQUAL";// 等于
                }
            }
            entity.setArrow(arrow);

            // 将相同的 CCCC 存入列表中
            ccccMap.computeIfAbsent(cccc, k -> new ArrayList<>()).add(entity);
        }

        // 将结果转换为列表
        for (Map.Entry<String, List<XjSelfObsEntity>> entry : ccccMap.entrySet()) {
            Map<String, Object> record = new HashMap<>();
            String ccccKey = entry.getKey();
            List<XjSelfObsEntity> entityList = entry.getValue();

            record.put("CCCC", ccccKey);
            record.put("data", entityList); // 将 list 放入 "data" 中
            result.add(record);
        }
        // 返回响应
        return ResponseJson.success(result);
    }


}
